const express = require('express')
const cors = require('cors')
const session = require('express-session')
const bodyParser = require('body-parser')
const joi = require('@hapi/joi')

// 导入nodejs-websocket模块
var ws = require("nodejs-websocket");
//生成jwt
const jwt = require('jsonwebtoken')

//创建服务器实例对象
const app = express()
//配置session中间件
/* app.use(session({
    secret: 'keyboardCat',//secret 可以为任意字符串
    resave: false,//固定写法
    saveUninitialized: true,//固定写法
})) */
//在路由之前开启跨域
app.use(cors())
//配置解析表单的中间件 只能解析app.../x ww 格式
app.use(express.urlencoded({ extended: false }))

//封装res函数
app.use((req, res, next) => {
    //status=1 表示失败  err错误对象或描述字符串
    res.cc = function (err, status = 1) {
        res.send({
            status,
            data: err instanceof Error ? err.message : err,
        })
    }
    next()
})

//解析客户端发送过来的jwt 转变为json
const expressJwt = require('express-jwt')
const config = require('./config')
app.use(expressJwt.expressjwt({ secret: config.jwtSecretKey, algorithms: ["HS256"] }).unless({ path: [/^\/email|img/] }))


//公开静态文件
app.use('/img/', express.static('./public/'))
// 挂载处理post请求的插件
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
//导入使用路由
const loginRe = require('./router/users/user')
//登录和注册 发送邮箱
app.use('/email', loginRe)
//获取用户基本信息
const userinfo = require('./router/users/userinfo')
app.use('/myUserinfo', userinfo)
//更新用户基本信息
const updUser = require('./router/users/updUser')
app.use('/upduser', updUser)
//上传图片
const uploadPicture = require('./router/uploadPicture/uploadPicture')
app.use('/uploadPicture', uploadPicture)
//发表自己写的文章 和获取
const uploadContent = require('./router/uploadContent/uploadContent')
app.use('/writeArticle', uploadContent)
app.use('/email/writeArticle', uploadContent)
//评论区域
const discuss = require('./router/discuss/discuss')
app.use('/discuss', discuss)
app.use('/email/discuss', discuss)
//定义错误级别中间件
app.use((err, req, res, next) => {
    console.log(err);
    //验证失败
    if (err instanceof joi.ValidationError)
        res.send({
            status: 1,
            data: err,
        })
    //身份认证
    if (err.name === 'UnauthorizedError')
        return res.send({
            status: 1,
            data: '身份认证失败',
        })
    //未知的错误
    res.send({
        status: 1,
        data: err,
    })
})



// 向所有连接的客户端广播
function boardcast(obj) {
    server.connections.forEach(function (conn) {
        conn.sendText(JSON.stringify(obj));
    })
}


var server = ws.createServer(function (conn) {
    console.log("开启ws服务");
    conn.on("text", function (data) {
        boardcast(data)
    })
    conn.on("close", function (code, reason) {
        console.log("关闭连接")
    })
    conn.on("error", function (code, reason) {
        console.log("异常关闭")
    })
}).listen(3000)


app.listen(3100, () => {
    console.log("localhost:3100");
})
